<template>
	<view class="content">

		<image style="width:100%;position: absolute;bottom:0;left:0;width:100%;" mode="widthFix"
			src="../../static/1.svg"></image>

		<view class="loginBox">
			<h3 style="text-align: center;margin-bottom:120rpx;">欢迎登录智学博客</h3>
			<view class="inputBox">
				<view class="ipt">
					<uni-icons type="contact" size="24" color="rgb(66,157,250)"></uni-icons>
					<input type="text" value="" v-model="user.phoneNum" placeholder="请输入手机号" />
				</view>
				<view class="ipt" v-if="psw">
					<uni-icons type="eye" size="24" color="rgb(66,157,250)"></uni-icons>
					<input type="password" value="" v-model="user.password" placeholder="请输入密码" />
				</view>
				<view class="ipt" v-if="msg">
					<uni-icons type="checkmarkempty" size="24" color="rgb(66,157,250)"></uni-icons>
					<input type="text" value="" v-model="user.verificationCode" placeholder="请输入验证码" />
					<view class="yzm" :class="{ disabled: isCountingDown }" @click="getVerificationCode()">
						{{ countdownText }}
					</view>
				</view>
				<button v-if="login1" @click="handleLogin()">登录</button>
				<button v-if="login2" @click="handleLoginByCode()">登录</button>
				<view class="forgetPwd">
					<button class="new-forgetPwd left-text">
						<text>忘记密码</text>
					</button>
					<button class="new-forgetPwd right-text" @click="navigateToRegister()">
						<text>前往注册</text>
					</button>
				</view>
				<button v-if="but" class="new-forgetPwd" @click="toggleInput()">
					<text>密码登录</text>
				</button>
			</view>
			<view class="tipbox">
				<view class="txt">
					—— 其他登录方式 ——
				</view>
				<view class="otherUser">
					<uni-icons type="qq" size="40" color="rgb(66,157,250)"></uni-icons>
					<uni-icons type="weixin" size="40" color="rgb(2,187,17)"></uni-icons>
					<uni-icons type="email-filled" size="40" color="rgb(170, 170, 255)"
						@click="toggleEmail()"></uni-icons>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 定义一个 user 对象来保存用户名和密码
				psw: true,
				msg: false,
				but: false,
				login1: true,
				login2: false,
				user: {
					phoneNum: '',
					password: '',
					verificationCode: '',
				},
				socket: null,
				countdown: 60,
				isCountingDown: false
			};
		},
		methods: {
			async handleLogin() {
				// 检查输入是否为空
				if (!this.user.phoneNum || !this.user.password) {
					uni.showToast({
						title: '请输入手机号和密码',
						icon: 'none'
					});
					return;
				}
				uni.clearStorageSync();
				try {
					// 发送登录请求
					const res = await uni.request({
						url: 'http://localhost:9091/font/sso/login',
						method: 'POST',
						data: this.user,
						header: {
							'Content-Type': 'application/json' // POST 数据内容类型
						}
					});
					console.log("后端响应:", res);
					// 处理服务器返回的数据
					if (res.data.code == 2001) {
						uni.showToast({
							title: '登录成功',
							duration: 2000
						});
						// 将生成的token存放到localStorage
						const userVisitToken = res.data.data.visitToken;
						const userRefreshToken = res.data.data.refreshToken;
						const userId = res.data.data.id;
						console.log(res.data.data.visitToken);
						console.log(res.data.data.refreshToken);
						console.log(res.data.data.id);
						uni.setStorage({
							key: "VisitToken",
							data: userVisitToken
						});
						uni.setStorage({
							key: "RefreshToken",
							data: userRefreshToken
						});
						uni.setStorage({
							key: "UserId",
							data: userId
						})
						const userDataString = localStorage.getItem("UserId");
						const userData = JSON.parse(userDataString);
						const sessionId = userData.data;
						this.socket = new WebSocket("ws://localhost:10010/websocket-endpoint/" + sessionId);
						this.socket.onopen = function(e) {
							console.log("Connected");
						};
						this.socket.onmessage = function(event) {
							uni.showModal({
								title: '提示',
								content: '您好，您的账号在其他设备登录，如果非本人操作，请尽快修改密码，避免账号丢失。',
								showCancel: false, // 隐藏取消按钮
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
										console.log('用户点击确定');
										//清空localStorage中的所有token，并返回到home页
										localStorage.removeItem('VisitToken');
										localStorage.removeItem('RefreshToken');
										localStorage.removeItem('UserId');
										window.location.href = "/#/pages/home/home";
									}
								}
							});
						};
						window.location.href = "/#/pages/home/home"
						// 进行其他操作，例如跳转页面等
						//发送专门的WebSocket请求，建立长连接
					} else {
						uni.clearStorageSync()
						switch (res.data.code) {
							case 4002:
								uni.showToast({
									title: '用户名或密码错误',
									duration: 2000,
								})
								break;
							case 2005:
								uni.showModal({
									title: '提示',
									content: '当前账号已有其他设备登录，是否继续登录？',
									success: (res) => {
										if (res.confirm) {
											console.log('用户点击确定');
											// 这里可以添加你的登录逻辑
											this.continueLogin();
											const userVisitToken = res.data.data.visitToken;
											const userRefreshToken = res.data.data.refreshToken;
											const userId = res.data.data.id;
											console.log(res.data.data.visitToken);
											console.log(res.data.data.refreshToken);
											console.log(res.data.data.id);
											uni.setStorage({
												key: "VisitToken",
												data: userVisitToken
											});
											uni.setStorage({
												key: "RefreshToken",
												data: userRefreshToken
											});
											uni.setStorage({
												key: "UserId",
												data: userId
											})
											this.socket = new WebSocket(
												"ws://localhost:10010/websocket-endpoint?useerId=" +
												userId);
											this.socket.onopen = function(e) {
												console.log("Connected");
											};
											this.socket.onmessage = function(event) {
												var msg = JSON.parse(event.data);
												alert(msg.text); // 显示消息
											};
											window.location.href = "/#/pages/home/home"
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
								break;
							case 4005:
								uni.showToast({
									title: '已登录，请勿重复登录',
									duration: 2000,
								})
								break;
							default:
								uni.showToast({
									title: '用户不存在,请注册',
									duration: 2000,
								})
								break;
						}
					}
				} catch (error) {
					console.error('登录请求错误:', error);
					if (error.errMsg.indexOf('request:fail') !== -1) {
						wx.showToast({
							title: '网络异常',
							icon: "error",
							duration: 2000
						})
					} else {
						wx.showToast({
							title: '未知异常',
							duration: 2000
						})
					}
				}
			},

			async continueLogin() {
				// 发送登录请求
				try {
					const res = await uni.request({
						url: 'http://localhost:9091/font/sso/loginContinue',
						method: 'GET',
						header: {
							'Content-Type': 'application/json' // GET 数据内容类型
						}
					});
					console.log("后端响应:", res);
					// 处理服务器返回的数据
					uni.showToast({
						title: '登录成功',
						duration: 2000
					});
					// 将生成的token存放到localStorage
					const userVisitToken = res.data.data.visitToken;
					const userRefreshToken = res.data.data.refreshToken;
					const userId = res.data.data.id;
					console.log(res.data.data.visitToken);
					console.log(res.data.data.refreshToken);
					console.log(res.data.data.id);
					uni.setStorage({
						key: "VisitToken",
						data: userVisitToken
					});
					uni.setStorage({
						key: "RefreshToken",
						data: userRefreshToken
					});
					uni.setStorage({
						key: "UserId",
						data: userId
					})
					window.location.href = "/#/pages/home/home"
					// 进行其他操作，例如跳转页面等
				} catch (error) {
					console.error('登录请求错误:', error);
					if (error.errMsg.indexOf('request:fail') !== -1) {
						wx.showToast({
							title: '网络异常',
							icon: "error",
							duration: 2000
						})
					} else {
						wx.showToast({
							title: '未知异常',
							duration: 2000
						})
					}
				}

			},

			navigateToRegister() {
				// 如果使用的是 vue-router
				this.$router.push('/pages/register/index');
				// 或者直接使用 window 对象
				// window.location.href = '/pages/register/index';
			},

			toggleInput() {
				// 取反 psw 和 msg 的值
				this.psw = true;
				this.msg = false;
				this.but = false;
				this.login1 = true;
				this.login2 = false;
			},

			toggleEmail() {
				// 取反 psw 和 msg 的值
				this.psw = false;
				this.msg = true;
				this.but = true;
				this.login1 = false;
				this.login2 = true;
			},

			async getVerificationCode() {
				if (!this.user.phoneNum) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
					return;
				}

				try {
					// 构建带有查询参数的URL
					const url =
						`http://localhost:9091/font/sso/getCode?phoneNum=${encodeURIComponent(this.user.phoneNum)}`;

					// 发送 GET 请求
					const res = await uni.request({
						url: url,
						method: 'GET',
						header: {
							'Content-Type': 'application/json'
						}
					});
					if (this.isCountingDown) return;
					this.isCountingDown = true;
					let interval = setInterval(() => {
						if (this.countdown === 0) {
							clearInterval(interval);
							this.countdown = 60;
							this.isCountingDown = false;
						} else {
							this.countdown--;
						}
					}, 1000);
					console.log("发送验证码");
					console.log("后端响应:", res);

					// 处理服务器返回的数据
					if (res.statusCode === 200 && res.data.code === 2001) {
						uni.showToast({
							title: '验证码发送成功',
							duration: 2000
						});
						// 进行其他操作，例如显示验证码或跳转页面等
					} else {
						uni.showToast({
							title: '验证码发送失败',
							duration: 2000
						});
					}
				} catch (error) {
					console.error('请求错误:', error);
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					});
				}
			},

			async handleLoginByCode() {
				if (!this.user.phoneNum || !this.user.verificationCode) {
					uni.showToast({
						title: '请输入手机号和验证码',
						icon: 'none'
					});
					return;
				}
				uni.clearStorageSync();
				try {
					// 发送登录请求
					const res = await uni.request({
						url: 'http://localhost:9091/font/sso/loginByCode',
						method: 'POST',
						data: this.user,
						header: {
							'Content-Type': 'application/json' // POST 数据内容类型
						}
					});
					console.log(res);
					if (res.data.code == 2001) {
						uni.showToast({
							title: '登录成功',
							duration: 2000
						});
						// 将生成的token存放到localStorage
						const userVisitToken = res.data.data.visitToken;
						const userRefreshToken = res.data.data.refreshToken;
						const userId = res.data.data.id;
						console.log(res.data.data.visitToken);
						console.log(res.data.data.refreshToken);
						console.log(res.data.data.id);
						uni.setStorage({
							key: "VisitToken",
							data: userVisitToken
						});
						uni.setStorage({
							key: "RefreshToken",
							data: userRefreshToken
						});
						uni.setStorage({
							key: "UserId",
							data: userId
						})
						window.location.href = "/#/pages/home/home"
						// 进行其他操作，例如跳转页面等
					} else {
						uni.clearStorageSync()
						switch (res.data.code) {
							case 5005:
								uni.showToast({
									title: '验证码错误',
									duration: 2000,
									icon: 'error',
								})
								break;
							default:
								uni.showToast({
									title: '用户不存在,请注册',
									duration: 2000,
								})
								break;
						}
					}
				} catch (error) {
					console.error('请求错误:', error);
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					});
				}

			},
		}
	};
</script>

<style scoped>
	svg {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 40%;
		box-sizing: border-box;
		display: block;
		background-color: #ffffff;
	}

	.loginBox {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -60%);
		width: 90%;
		border-radius: 20rpx;
		padding: 60rpx;
		box-sizing: border-box;
	}

	h3 {
		color: rgb(66, 157, 250);
		font-size: 40rpx;
		letter-spacing: 10rpx;
		margin-bottom: 40rpx;
	}

	.inputBox {}

	.ipt {
		height: 86rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-bottom: 40rpx;
		background-color: #f5f5f5;
		border-radius: 10rpx;
		padding-left: 10rpx;
	}

	.ipt input {
		margin-left: 20rpx;
		font-size: 28rpx;
	}

	.ipt input {
		margin-left: 20rpx;
	}

	.forgetPwd {
		display: flex;
		/* 使用 Flexbox 布局 */
		justify-content: space-between;
		/* 子元素两端对齐 */
		align-items: center;
		/* 垂直居中对齐 */
		margin-top: 10rpx;
		text-align: end;
		padding: 0 10rpx;
		border: none;
		/* 去掉边框 */
		box-shadow: none;
		/* 去掉阴影 */
		background-color: transparent;
		/* 设置背景为透明 */
	}

	.forgetPwd {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 5rpx;
		/* 减少顶部外边距 */
		text-align: end;
		padding: 0 5rpx;
		/* 减少左右内边距 */
		border: none;
		box-shadow: none;
		background-color: transparent;
	}

	.new-forgetPwd {
		color: gray;
		background-color: transparent;
		text-align: center;
		border: none;
		box-shadow: none;
		cursor: pointer;
		font-size: 12px;
		/* 减小字体大小 */
		line-height: 1.2;
		/* 减小行高 */
		padding: 0;
		/* 移除内边距 */
	}

	.left-text,
	.right-text {
		text-align: start;
		font-size: 12px;
		/* 减小字体大小 */
		line-height: 1.2;
		/* 减小行高 */
	}

	button {
		margin-top: 20rpx;
		line-height: 85rpx;
		text-align: center;
		background: rgb(66, 157, 250);
		border-radius: 40rpx;
		color: #fff;
		margin-top: 40rpx;
	}

	.tip {
		text-align: center;
		font-size: 28rpx;
		position: fixed;
		bottom: 50rpx;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #f4f4f4;
	}

	.tipbox {
		text-align: center;
		margin-top: 60rpx;
	}

	.otherUser {
		margin-top: 30rpx;
		justify-content: center;
		display: flex;
		justify-content: center;
	}

	.txt {
		font-size: 28rpx;
		color: #cbcbcb;
	}

	.otherUser .uni-icons {
		margin-left: 20rpx;
	}

	.yzm {
		text-align: end;
		font-size: 24rpx;
		background: linear-gradient(to right, rgb(66, 157, 250), rgb(0, 170, 127));
		height: 60rpx;
		width: 150rpx;
		line-height: 60rpx;
		text-align: center;
		border-radius: 10rpx;
		color: #fff;
	}
</style>